<template name="home">
  <view>
    <scroll-view>
      <!-- 轮播 -->
      <swiper
        class="screen-swiper square-dot"
        :indicator-dots="true"
        :circular="true"
        :autoplay="true"
        interval="5000"
        duration="500"
        :style="[{ animation: 'show 0.2s 1' }]"
      >
        <swiper-item v-for="(item, index) in swiperList" :key="index" @click="viewImage(index)">
          <image :src="item.url" mode="aspectFill" v-if="item.type == 'image'"></image>
          <video
            :src="item.url"
            autoplay
            loop
            muted
            :show-play-btn="false"
            :controls="false"
            objectFit="cover"
            v-if="item.type == 'video'"
          ></video>
        </swiper-item>
      </swiper>

      <!-- 常用服务 -->
      <view v-for="(item, index) in appConfigTypeList" :key="index">
        <view class="cu-bar bg-white solid-bottom" :style="[{ animation: 'show 0.5s 1' }]">
          <view class="action">
            <text class="cuIcon-title" :class="item.value == 'common' ? 'text-blue' : 'text-yellow'"></text>
            {{ item.text }}
          </view>
        </view>

        <view class="cu-list grid col-4 text-sm">
					<!-- cu-item => 控制boder样式 -->
          <view
            class=" cu-item animation-slide-bottom card"
            :style="[{ animationDelay: (index + 1) * 0.05 + 's' }]"
            v-for="(value, ind) in item.appRouteList"
            :key="ind"
            @tap="goPage(value.routeIndex)"
            v-show="value.status == 1"
          >
            <view class="padding text-center">
              <image :src="value.icon.indexOf('http') != -1 ? value.icon : imageUrl(value.icon)" style="width: 28px; height: 28px"></image>
              <view class="margin-top-xs">{{ value.title }}</view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
    <tabbar :value="0"></tabbar>
		<sacanCodePopup ref="sacanCodePopupRef"></sacanCodePopup>
		<!-- <u-modal :show="showModal" title="111" content='content' style="z-index: 1000000000"></u-modal> -->
		<u-overlay :show="showModal" @click="show = false" zIndex="1000000000">
			<u-modal :show="showModal" content='请先补填工时' @confirm="handleConfirm"></u-modal>
		</u-overlay>
  </view>
</template>

<script>
import { us, os, xm, finance } from '@/common/util/work.js'
import http from '@/utils/request/index.js'
import socket from '@/common/js-sdk/socket/socket.js'
import tabbar from '@/components/tabbar.vue'
import sacanCodePopup from './components/sacanCodePopup.vue'
import { imageUrl } from '@/utils/common.js'
import { initDictOptions } from '@/utils/JDictSelectUtil.js'
sysAppRouteList
import {
  sysAppRouteList,
  querySuccessResignByEmployeeId,
  queryTempData,
  editResignByEmployeeId, // 离职申请单清空新增数据
  queryHandleAdjustmentByEmployeeId,
  queryAdjustmentTempData,
	queryHrPostRequirement,
	clearAdjustmentEmployeeId, // 人员调岗清空新增数据
	clearRequirementEmployeeId, // 岗位需求申请清空新增数据
	clearRegularEmployeeId, // 转正申请清空新增数据
	queryEmployeeRegularTempData,
	queryEmployeeRegularSuccess
} from '@/api/index.js'
import {
  queryImages, // 轮播图
} from '@/api/index.js'
import {getTaskInputUserType,getTaskInputDataStatus} from '@/api/taskInput/index.js'

export default {
  name: 'home',
  components: {
    tabbar,
		sacanCodePopup
  },
  onLoad(options) {
		this.loadData() // 获取列表
		uni.hideTabBar()
		if (options.ACCESS_TOKEN) {
		  uni.clearStorageSync('ACCESS_TOKEN')
		  uni.setStorageSync('ACCESS_TOKEN', options.ACCESS_TOKEN)
		}
		this.getSwiperImages() // 获取轮播图
  },
	onShow() {
		// 清空选择通知公告选择的人员
		if (this.$store.state.selectPerson) {
			this.$store.dispatch('actionsSetSelectPerson', '')
		}
		// 判断是否补填上周工时
		this.hanleSubmitLastWeekTaskTime('force')
	},
  data() {
    return {
		showModal: false,
      imageUrl,
      appConfigTypeList: [], // 排版信息
      swiperList: [], // 轮播图
      middleApps: [
        { icon: 'line2_icon1.png', title: '审批', text: '个人审批' },
        { icon: 'line2_icon2.png', title: '审批稿', text: '审批草稿箱' },
      ],
      usList: us.data, // 常用服务
      osList: os.data, // 财务类审批
      xmList: xm.data, // 项目类审批
      financeList: finance.data, // 财务管理
      msgCount: 0, // 通知公告的数量
      dot: {
        mailHome: false,
      },
      isSubmit: false,
			// 用来控制工时填报的数据状态
			iptStatus:'',
			// 用来控制工时填报的用户类型
			iptUserType:'',
			btnClicked:false
    }
  },
  methods: {
    // 获取轮播图
    getSwiperImages() {
      var params = {
        suitability: 2,
      }
      queryImages(params)
        .then((res) => {
          if (res.result && res.result.length) {
            res.result.map((value) => {
              value.url = imageUrl(value.imgurl)
              value.type = 'image'
              value.link = value.imglink
              return value
            })
          }
          this.swiperList = res.result
        })
        .catch((res) => {})
    },
	// 获取首页排版
    loadData() {
		// 获取首页信息
		this.$store.dispatch('actionsSetIndexList').then(res =>{
			if (res.result.appMenu && res.result.appMenu.length) {
				res.result.appMenu.map(value => {
					if (value.appRouteList && value.appRouteList.length) {
						value.appRouteList.sort((a, b) => a.sort - b.sort);
					}
				})
			}
			this.appConfigTypeList = res.result.appMenu
		})
    },

    // 点击预览
    viewImage(url, ind) {
      var urlArr = []
      this.swiperList.map((value) => {
        if (value.type == 'image') {
          urlArr.push(value.url)
        }
      })
      uni.previewImage({
        urls: urlArr,
        current: ind,
        longPressActions: {
          itemList: ['保存图片'],
          success: function (data) {
            uni.downloadFile({
              url: url,
              success: (result) => {
                if (result.statusCode === 200) {
                  //文件保存到本地
                  uni.saveImageToPhotosAlbum({
                    filePath: result.tempFilePath, //临时路径
                    success: function (ress) {
                      uni.showToast({
                        icon: 'none',
                        mask: true,
                        title: '文件已保存：' + ress.path, //保存路径
                        duration: 3000,
                      })
                    },
                  })
                }
              },
              fail: (err) => {
                uni.showToast({
                  icon: 'none',
                  mask: true,
                  title: '失败请重新下载',
                })
              },
            })
          },
          fail: function (err) {
            console.log(err.errMsg)
          },
        },
      })
    },

    initMenu() {
      this.onSocketOpen() // 启动webSocket
      this.onSocketReceive() // webSocket收到的信息 - 用于判断邮件通知邮件是否有通知
      this.loadCount(0)
    },
	scanCodeContent(content) {
		// 获取的数据传入到后台
		http.post('/api/erp/finance/record/erpFinancePaymentAgainstDocumentsRecord/scanCode', content).then(res =>{
			// this.appConfigTypeList = res.result.appMenu
			if (res.success) {
				// this.$refs.sacanCodePopupRef.edit(res.result)
				// this.$refs.sacanCodePopupRef.show = true
				var result = JSON.stringify(res.result)
				uni.navigateTo({
					url: `/pages/finance/ErpFinanceScanForm?model=${result}`
				})
			} else {
				this.$utils.toast(res.message)
			}
		})
	},
    async goPage(page) {
		var _this = this
		if (!page) {
			return false
		}
		if (!page.includes('/')) {
		  this.$utils.toast('暂未开放')
		  return false
		}
		if (page == '/') {
			// 扫一扫
			// #ifndef H5
			uni.scanCode({
				onlyFromCamera: true,
				success: function (res) {
					var content = res.result ? JSON.parse(res.result) : ''
					if (!content || !content.billNo || !content.billType) {
						uni.showToast({
							title: '该二维码无效，请重新生成扫描',
							icon: 'none'
						})
						return
					}
					_this.scanCodeContent(content)
				}
			})
			// #endif
		}
      
      // 当是人员调岗单
      if (page == '/pages/work/ErpHrEmployeeAdjustPostBillForm') {
        this.isApprovalSuccessful(page)
        return false
      }
      // 当是离职申请单
		if (page == '/pages/hr/EmploeeLeaveApply') {
			this.getEmploeeLeaveApply(page)
			return false
		}
			// 当是岗位需求申请
			// if (page == '/pages/hr/ErpHrPostRequirementBillForm') {
			//   this.isAppPostRequirementBill(page)
			//   return false
			// }
			// 当是转正申请
		if (page == '/pages/hr/EmploeeRegularApply') {
			this.isEmploeeRegularApply(page)
			return false
		}
		if (page == '/pages/message/message') {
			uni.switchTab({
			  url: page,
			})
		} else if (page == '/pages/hr/CarUserInfoForm') {
			uni.navigateTo({
			  url: '/pages/hr/CarUserInfoList',
			})
		} else if(page == '/pages/taskTimeSubmit/submitThisWeekTaskTime'){
		  /* 填报工时*/
			await this.hanleSubmitThisWeekTaskTime(page)
			
		} else if(page == '/pages/taskTimeSubmit/submitLastWeekTaskTime'){
			/* 补填工时 */
			await this.hanleSubmitLastWeekTaskTime()
		}else {
			uni.navigateTo({ url: page })
		}
    },
		async isEmploeeRegularApply(page){
			if (this.isSubmit) {
			  // 防止多次提交
			  return
			}
			this.isSubmit = true
			let userinfo = uni.getStorageSync('userInfo')
			//判断是否已经审批成功了
			queryEmployeeRegularSuccess({ employeeId: userinfo.empId }).then(async (res) => {
			  if (res.success) {
			    let data = await res.result
					if(data.success>0){
						this.isSubmit = false
						uni.showModal({
						  title: '转正审批单提示',
						  content: '您的审批单已经审核通过了，请勿重复提交审批！',
						  showCancel: false,
						})
					}else if(data.handle>0){
						this.isSubmit = false
						uni.showModal({
						  title: '转正审批单提示',
						  content: '您的审批单正在处理中，请勿重复提交审批！',
						  showCancel: false,
						})
					} else {
			      //判断是否存在未提交的审批单
			      queryEmployeeRegularTempData({ employeeId: userinfo.empId }).then(async (res) => {
			        var _this = this
			        if (res.success) {
			          this.isSubmit = false
			          let data = await res.result.records
			          if (data[0]) {
			            uni.showModal({
			              title: '转正审批单提示',
			              content: '您当前存在未提交的审批单信息，是否继续编辑？点击【放弃编辑】按钮新增审批单信息。',
			              cancelText: '放弃编辑',
			              confirmText: '继续编辑',
			              success: async (res) => {
			                if (res.confirm) {
			                  uni.navigateTo({
			                    url: page + '?id=' + data[0].id,
			                  })
			                } else {
			                  uni.navigateTo({
			                    url: page,
			                  })
			                  _this.cancelTemp(clearRegularEmployeeId)
			                }
			              },
			            })
			          } else {
			            uni.navigateTo({
			              url: page,
			            })
			          }
			        }
			      })
			    }
			  }
			})
		},
		async isAppPostRequirementBill(page){
			if (this.isSubmit) {
			  // 防止多次提交
			  return
			}
			this.isSubmit = true
			let userinfo = uni.getStorageSync('userInfo')
			queryHrPostRequirement({ employeeId: userinfo.empId }).then(async (res) => {
				var _this = this
				if (res.success) {
				  this.isSubmit = false
				  let data = await res.result.records
				  if (data[0]) {
				    uni.showModal({
				      title: '岗位需求审批单提示',
				      content: '您当前存在未提交的审批单信息，是否继续编辑？点击【放弃编辑】按钮新增审批单信息。',
				      cancelText: '放弃编辑',
				      confirmText: '继续编辑',
				      success: async (res) => {
				        if (res.confirm) {
				          uni.navigateTo({
				            url: page + '?id=' + data[0].id,
				          })
				        } else {
				          uni.navigateTo({
				            url: page,
				          })
				          _this.cancelTemp(clearRequirementEmployeeId)
				        }
				      },
				    })
				  } else {
				    uni.navigateTo({
				      url: page,
				    })
				  }
				}
			})
		},
    async isApprovalSuccessful(page) {
      if (this.isSubmit) {
        // 防止多次提交
        return
      }
      this.isSubmit = true
      let userinfo = uni.getStorageSync('userInfo')
      //判断是否已经审批成功了
      queryHandleAdjustmentByEmployeeId({ employeeId: userinfo.empId }).then(async (res) => {
        if (res.success) {
          let data = await res.result
          if (data.handle > 0) {
            this.isSubmit = false
            uni.showModal({
              title: '人员调岗单提示',
              content: '您的审批单正在处理中，请勿重复提交审批！',
              showCancel: false,
            })
          } else {
            //判断是否存在未提交的审批单
            queryAdjustmentTempData({ employeeId: userinfo.empId }).then(async (res) => {
              var _this = this
              if (res.success) {
                this.isSubmit = false
                let data = await res.result.records
                if (data[0]) {
                  uni.showModal({
                    title: '人员调岗单提示',
                    content: '您当前存在未提交的审批单信息，是否继续编辑？点击【放弃编辑】按钮新增审批单信息。',
                    cancelText: '放弃编辑',
                    confirmText: '继续编辑',
                    success: async (res) => {
                      if (res.confirm) {
                        uni.navigateTo({
                          url: page + '?id=' + data[0].id,
                        })
                      } else {
                        uni.navigateTo({
                          url: page,
                        })
                        _this.cancelTemp(clearAdjustmentEmployeeId)
                      }
                    },
                  })
                } else {
                  uni.navigateTo({
                    url: page,
                  })
                }
              }
            })
          }
        }
      })
    },

    // 离职申请单页面跳转
    async getEmploeeLeaveApply(page) {
      if (this.isSubmit) {
        // 防止多次提交
        return
      }
      this.isSubmit = true
      querySuccessResignByEmployeeId({ employeeId: uni.getStorageSync('userInfo').empId }).then(async (res) => {
        if (res.success) {
          this.isSubmit = false
          let data = await res.result
          if (data.success > 0) {
            uni.showModal({
              title: '离职审批单提示',
              content: '您的审批单已经审核通过了，请勿重复提交审批！',
              showCancel: false,
            })
          } else if (data.handle > 0) {
            uni.showModal({
              title: '离职审批单提示',
              content: '您的审批单正在处理中，请勿重复提交审批！',
              showCancel: false,
            })
          } else {
            //判断是否存在未提交的审批单
            queryTempData({ employeeId: uni.getStorageSync('userInfo').empId }).then(async (res) => {
              var _this = this
              if (res.success) {
                this.isSubmit = false
                let data = await res.result.records
                if (data[0]) {
                  uni.showModal({
                    title: '离职审批单提示',
                    content: '您当前存在未提交的审批单信息，是否继续编辑？点击【放弃编辑】按钮新增审批单信息。',
                    cancelText: '放弃编辑',
                    confirmText: '继续编辑',
                    success: async (res) => {
                      if (res.confirm) {
                        uni.navigateTo({
                          url: page + '?id=' + data[0].id,
                        })
                      } else {
                        uni.navigateTo({
                          url: page,
                        })
                        _this.cancelTemp(editResignByEmployeeId)
                      }
                    },
                  })
                } else {
                  uni.navigateTo({
                    url: page,
                  })
                }
              }
            })
          }
        }
      })
    },
	/* 填报工时判断 */
    async hanleSubmitThisWeekTaskTime(page){
			// 添加人员身份判断，如果是白名单，不需要填报
			const _userTypeData = await getTaskInputUserType()
			// 生产人员类型
			this.iptUserType = _userTypeData.result.type
			if(this.iptUserType === 'white'){
				this.$utils.toast('您无需填报工时')
				return
			}
			const _iptDataStatusData = await getTaskInputDataStatus()
			// 数据填报状态
			const _iptDataStatus = _iptDataStatusData.result
			// thisDay：今天是否已填。
			// lastWeek：是否有补填
			/*
				no  需要填写,但是没填
				not 不需要填
				yes  已填
			*/
			const { thisDay,lastWeek,thisDayFillIn } = _iptDataStatus
			if (lastWeek === 'no'){
				this.$utils.toast('请先补填工时!')
				this.iptStatus = ''
				return
			}
			if (thisDayFillIn === 'miss'){
				// this.$utils.toast('今日已统计,请于明日补填！')
				this.iptStatus = 'viewThisDay'
			}else{
				if(thisDay=='not'){
					this.$utils.toast('无填报任务!')
					this.iptStatus = ''
					return
				}else if(thisDay=='yes'){
					// this.$utils.toast('今日工时已填报!')
					this.iptStatus = 'viewThisDay'
				}else if(thisDay=='vacation'){
					this.$utils.toast('当日为假勤日，无需填报工时!')
					this.iptStatus = ''
					return
				}else{
					this.iptStatus = 'add'
				}
			}
			uni.navigateTo({
				url:`${page}?userType=${this.iptUserType}&iptStatus=${this.iptStatus}`
			})
			
		},
		/* 补填工时判断 */
		async hanleSubmitLastWeekTaskTime(type){
			
			const _iptDataStatusData = await getTaskInputDataStatus()
			// 数据填报状态
			const _iptDataStatus = _iptDataStatusData.result
			const {lastWeek,lastWeekFillIn} = _iptDataStatus
			if (type && type == 'force') {
				if(lastWeek==='no'){
					this.iptStatus = 'fillLastWeek'
					this.showModal = true
				}
			} else {
				
				// if (lastWeekFillIn === 'miss') {
				// 	this.$utils.toast('工时已补填，无需再次补填')
				// 	this.iptStatus = ''
				// }
				// // 只有上周未正常填报，才可以进入界面
				// if(lastWeek==='yes'){
				// 	this.$utils.toast('工时已填报，无需补填')
				// 	this.iptStatus = ''
				// }else if(lastWeek === 'not'){
				// 	this.$utils.toast('无补填任务')
				// 	this.iptStatus = ''
				// }else if(lastWeek==='no'){
				// 	this.handleConfirm()
				// }
				
				if (lastWeekFillIn === 'miss') {
					this.iptStatus = 'viewLastWeek'
					this.handleConfirm()
					return
				}
				if(lastWeek === 'not'){
					this.$utils.toast('无需要补填的任务！')
					this.iptStatus = ''
				}else{
					this.iptStatus = 'viewLastWeek'
					this.handleConfirm()
				}
			}
		},
		handleConfirm () {
			uni.navigateTo({
				url:`/pages/taskTimeSubmit/submitLastWeekTaskTime?userType=${this.iptUserType}&iptStatus=${this.iptStatus}`
			})
			this.showModal = false
		},
		// 启动webSocket
    onSocketOpen() {
      socket.init('websocket')
    },

    cancelTemp(apiUrl) {
		if (apiUrl && typeof apiUrl == 'function') {
			apiUrl({ employeeId: uni.getStorageSync('userInfo').empId })
		}
    },
    onSocketReceive() {
      var _this = this
      socket.acceptMessage = function (res) {
        if (res.cmd == 'topic') {
          //系统通知
          _this.loadCount('1')
        } else if (res.cmd == 'user') {
          //用户消息
          _this.loadCount('2')
        } else if (res.cmd == 'email') {
          //邮件消息
          _this.loadEmailCount()
        }
      }
    },
    loadCount(flag) {
      let url = '/sys/annountCement/listByUser'
      this.$http.get(url).then((res) => {
        if (res.data.success) {
          let msg1Count = res.data.result.anntMsgTotal
          let msg2Count = res.data.result.sysMsgTotal
          this.msgCount = msg1Count + msg2Count
        }
      })
    },
    loadEmailCount() {
      this.dot.mailHome = true
    },
    getTtemDotInfo(item) {
      if (item.page === 'annotationList' && this.msgCount > 0) {
        return this.msgCount
      }
      return ''
    },
  },
}
</script>

<style scoped>
.cu-list.grid > .cu-item {
  padding: 0px 0px;
}
.line2-icon {
  width: 60px;
  height: 60px;
}

.warp {
	display: flex;
	align-items: center;
	justify-content: center;
	height: 100%;
}

.rect {
	width: 120px;
	height: 120px;
	background-color: #fff;
}
</style>
